package com.yami.shop.platform.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SkuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author yxf on 2022/11/25.
 */
@RestController
@Tag(name = "测试接口-商城代码不要用,给自动化测试用的")
@RequestMapping("/platform/test")
public class TestController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private ProductService productService;

    @Autowired
    private SkuService skuService;

    @PostMapping("/orderSettlement")
    @Operation(summary =  "订单结算", description = "订单结算")
    public ServerResponseEntity<Void> settlement(@RequestBody Long orderId) {
        Date date = DateUtil.offsetDay(new Date(), -20).toJdkDate();
        Order order = new Order();
        order.setOrderId(orderId);
        order.setUpdateTime(date);
        order.setFinallyTime(date);
        orderService.updateById(order);
        order = orderService.getById(orderId);
        if (!Objects.equals(order.getStatus(), OrderStatus.SUCCESS.value())) {
            ServerResponseEntity.fail(ResponseEnum.SHOW_FAIL, "订单未确认收货");
        }
        List<OrderItem> orderItems = orderItemService.list(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, order.getOrderNumber()));
        order.setOrderItems(orderItems);
        List<Order> orderList = Collections.singletonList(order);

        // 结算
        orderService.orderCommissionSettlement(orderList);

        // 移除缓存
        for (OrderItem orderItem : orderItems) {
            productService.removeProdCacheByProdId(orderItem.getProdId());
            skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());

        }
        return ServerResponseEntity.success();
    }
}
